package microservice

import (
	"hxy/repo/database"
	errors "hxy/repo/error"
	"os"
	"path"
	"strconv"

	"github.com/emicklei/go-restful/v3"
)

type DockerfielResponse struct {
	Exist      bool   `json:"exist"`
	Dockerfile string `json:"dockerfile"`
}
type DockerfileRequest struct {
	Gitid     uint   `json:"gitid"`
	Submodule string `json:"submodule"`
}
type DockerfileCreate struct {
	Req  DockerfileRequest  `json:"req"`
	Resp DockerfielResponse `json:"resp"`
}

func HandlerSubModuleGet(request *restful.Request, response *restful.Response) {
	var id = request.PathParameter("gitid")
	aid, _ := strconv.Atoi(id)
	list := GetSubModule(uint(aid))
	response.WriteAsJson(list)
}

func HandlerDockerfileDelivery(request *restful.Request, response *restful.Response) {
	reqdata := new(DockerfileRequest)
	request.ReadEntity(reqdata)
	gitmodel, _ := database.GitById(int(reqdata.Gitid))
	//submodules := DockerBuildPathofSubModule(gitmodel)

	dockerfile_path := path.Join(gitmodel.Path, reqdata.Submodule, "Dockerfile")

	_, err := os.Stat(dockerfile_path)
	var data DockerfielResponse
	if err != nil {
		data.Exist = false
		response.WriteAsJson(data)
		return
	} else {
		data.Exist = true
	}
	bytes_, err := os.ReadFile(dockerfile_path)
	if err != nil {
		errors.HandleInternalError(response, err)
		return
	}
	data.Dockerfile = string(bytes_)
	response.WriteAsJson(data)

}

func HandlerDockerfileCreate(request *restful.Request, response *restful.Response) {
	recdata := new(DockerfileCreate)
	request.ReadEntity(recdata)
	gitmodel, _ := database.GitById(int(recdata.Req.Gitid))
	//submodules := DockerBuildPathofSubModule(gitmodel)

	dockerfile_path := path.Join(gitmodel.Path, recdata.Req.Submodule, "Dockerfile")
	file, err := os.Create(dockerfile_path)
	if err != nil {
		errors.HandleInternalError(response, err)
		return
	}
	_, err = file.WriteString(recdata.Resp.Dockerfile)
	if err != nil {
		errors.HandleInternalError(response, err)
		return
	}
	response.WriteAsJson(recdata.Resp)
}

func HandlerAutoGenDockerfile(request *restful.Request, response *restful.Response) {
	reqdata := new(DockerfileRequest)
	request.ReadEntity(reqdata)
	gitmodel, _ := database.GitById(int(reqdata.Gitid))
	_path := path.Join(gitmodel.Path, reqdata.Submodule)
	_, genfile := autoGenDockerfile(_path)
	var ponsdata = DockerfielResponse{
		Exist:      true,
		Dockerfile: genfile,
	}
	response.WriteAsJson(ponsdata)
	// autoGenDockerfile
}

func HandlerAutoGenK8sYaml(request *restful.Request, response *restful.Response) {
	reqdata := new(GenCodeRequest)
	request.ReadEntity(reqdata)
	gitmodel, _ := database.GitById(int(reqdata.Gitid))
	code_Gen := GenYamlByGitModle(gitmodel, reqdata.GenMode)
	reqdata.Gencode = code_Gen
	response.WriteAsJson(reqdata)
}
